import Koa from 'koa';
import bodyParser from 'koa-bodyparser';
import cors from '@koa/cors';
import router from './routes/index';

const app = new Koa();

// CORS 中间件
app.use(cors({
    origin: '*', // 允许所有来源
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
}));

// 错误处理中间件
app.use(async (ctx, next) => {
    try {
        await next();
    } catch (err: any) {
        ctx.status = err.status || 500;
        ctx.body = {
            success: false,
            error: err.message || '服务器内部错误'
        };
        ctx.app.emit('error', err, ctx);
    }
});

// 解析请求体
app.use(bodyParser());

// 路由
app.use(router.routes());
app.use(router.allowedMethods());

export default app; 